﻿using NLog;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using WTAppletProjectHTTPS.Models;

namespace WTAppletProjectHTTPS.Controllers
{
  
    public class PackagingStationChangeInformationConfirmationQueryController : ApiController
    {
        private static readonly Logger Logger = NLog.LogManager.GetCurrentClassLogger();

        // POST api/<controller>
        public async Task<HttpResponseMessage> Post([FromBody] PackagingStationChangeInformationConfirmationQuery PSCICQ)
        {
            ReturnObjectQuery RO = new ReturnObjectQuery();
            if (PSCICQ.PageNumber <= 0 || PSCICQ.PageSize <= 0)
            {
               
                RO.Status = HttpStatusCode.BadRequest;
                RO.Message = "分页参数无效";
                RO.Data = null;
                Logger.Error("分页参数无效");
                return Request.CreateResponse(HttpStatusCode.BadRequest, RO);
            }

            try
            {
                using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionName"].ConnectionString))
                {
                    await connection.OpenAsync();

                    var whereClause = "WHERE 1=1";
                    if (PSCICQ.PSCIC_ID != 0)
                    {
                        whereClause += " AND PSCICID = @ID";
                    }
                    if (!string.IsNullOrEmpty(PSCICQ.PSCIC_OperatorName))
                    {
                        whereClause += " AND PSCICOperatorName LIKE @OperatorName";
                    }
                    if (PSCICQ.PSCIC_ConfirmationTime.HasValue)
                    {
                        whereClause += " AND PSCICConfirmationTime = @ConfirmationTime";
                    }
                    if (!string.IsNullOrEmpty(PSCICQ.PSCIC_LineParting))
                    {
                        whereClause += " AND PSCICLineParting LIKE @LineParting";
                    }
                    if (!string.IsNullOrEmpty(PSCICQ.PSCIC_Channel))
                    {
                        whereClause += " AND PSCICChannel LIKE @Channel";
                    }
                    if (!string.IsNullOrEmpty(PSCICQ.PSCIC_PlasticBagFilmPhoto))
                    {
                        whereClause += " AND PSCICPlasticBagFilmPhoto LIKE @PlasticBagFilmPhoto";
                    }
                    if (!string.IsNullOrEmpty(PSCICQ.PSCIC_ThermalTransferLabelPhoto))
                    {
                        whereClause += " AND PSCICThermalTransferLabelPhoto LIKE @ThermalTransferLabelPhoto";
                    }
                    if (!string.IsNullOrEmpty(PSCICQ.PSCIC_ColorBoxPhoto))
                    {
                        whereClause += " AND PSCICColorBoxPhoto LIKE @ColorBoxPhoto";
                    }
                    if (!string.IsNullOrEmpty(PSCICQ.PSCIC_ColorBoxLabelPhoto))
                    {
                        whereClause += " AND PSCICColorBoxLabelPhoto LIKE @ColorBoxLabelPhoto";
                    }
                    if (!string.IsNullOrEmpty(PSCICQ.PSCIC_OuterBoxLabelPhoto))
                    {
                        whereClause += " AND PSCICOuterBoxLabelPhoto LIKE @OuterBoxLabelPhoto";
                    }

                    var query = $@"
                        SELECT 
                            PSCICID, PSCICOperatorName, PSCICConfirmationTime, PSCICLineParting, 
                            PSCICChannel, PSCICPlasticBagFilmPhoto, PSCICThermalTransferLabelPhoto, 
                            PSCICColorBoxPhoto, PSCICColorBoxLabelPhoto, PSCICOuterBoxLabelPhoto,PSCICCreateCreator,PSCICCreateTime,
                            COUNT(*) OVER() AS TotalCount
                        FROM 
                            (SELECT 
                                PSCICID, PSCICOperatorName, PSCICConfirmationTime, PSCICLineParting, 
                                PSCICChannel, PSCICPlasticBagFilmPhoto, PSCICThermalTransferLabelPhoto, 
                                PSCICColorBoxPhoto, PSCICColorBoxLabelPhoto, PSCICOuterBoxLabelPhoto,PSCICCreateCreator,PSCICCreateTime,
                                ROW_NUMBER() OVER(ORDER BY PSCICID) AS RowNum
                             FROM PackagingStationChangeInformationConfirmation {whereClause}) AS Result
                        WHERE 
                            RowNum BETWEEN @StartRow AND @EndRow
                        ORDER BY RowNum";

                    int startRow = (PSCICQ.PageNumber - 1) * PSCICQ.PageSize + 1;
                    int endRow = PSCICQ.PageNumber * PSCICQ.PageSize;

                    var parameters = new List<SqlParameter>
                    {
                        new SqlParameter("@StartRow", SqlDbType.Int) { Value = startRow },
                        new SqlParameter("@EndRow", SqlDbType.Int) { Value = endRow }
                    };
                    if (PSCICQ.PSCIC_ID != 0)
                    {
                        parameters.Add(new SqlParameter("@ID", SqlDbType.Int) { Value =PSCICQ.PSCIC_ID });
                    }
                    if (!string.IsNullOrEmpty(PSCICQ.PSCIC_OperatorName))
                    {
                        parameters.Add(new SqlParameter("@OperatorName", SqlDbType.NVarChar, 50) { Value = $"%{PSCICQ.PSCIC_OperatorName}%" });
                    }
                    if (PSCICQ.PSCIC_ConfirmationTime.HasValue)
                    {
                        parameters.Add(new SqlParameter("@ConfirmationTime", SqlDbType.DateTime) { Value = PSCICQ.PSCIC_ConfirmationTime });
                    }
                    if (!string.IsNullOrEmpty(PSCICQ.PSCIC_LineParting))
                    {
                        parameters.Add(new SqlParameter("@LineParting", SqlDbType.NVarChar, 50) { Value = $"%{PSCICQ.PSCIC_LineParting}%" });
                    }
                    if (!string.IsNullOrEmpty(PSCICQ.PSCIC_Channel))
                    {
                        parameters.Add(new SqlParameter("@Channel", SqlDbType.NVarChar, 50) { Value = $"%{PSCICQ.PSCIC_Channel}%" });
                    }
                    if (!string.IsNullOrEmpty(PSCICQ.PSCIC_PlasticBagFilmPhoto))
                    {
                        parameters.Add(new SqlParameter("@PlasticBagFilmPhoto", SqlDbType.NVarChar, 100) { Value = $"%{PSCICQ.PSCIC_PlasticBagFilmPhoto}%" });
                    }
                    if (!string.IsNullOrEmpty(PSCICQ.PSCIC_ThermalTransferLabelPhoto))
                    {
                        parameters.Add(new SqlParameter("@ThermalTransferLabelPhoto", SqlDbType.NVarChar, 100) { Value = $"%{PSCICQ.PSCIC_ThermalTransferLabelPhoto}%" });
                    }
                    if (!string.IsNullOrEmpty(PSCICQ.PSCIC_ColorBoxPhoto))
                    {
                        parameters.Add(new SqlParameter("@ColorBoxPhoto", SqlDbType.NVarChar, 100) { Value = $"%{PSCICQ.PSCIC_ColorBoxPhoto}%" });
                    }
                    if (!string.IsNullOrEmpty(PSCICQ.PSCIC_ColorBoxLabelPhoto))
                    {
                        parameters.Add(new SqlParameter("@ColorBoxLabelPhoto", SqlDbType.NVarChar, 100) { Value = $"%{PSCICQ.PSCIC_ColorBoxLabelPhoto}%" });
                    }
                    if (!string.IsNullOrEmpty(PSCICQ.PSCIC_OuterBoxLabelPhoto))
                    {
                        parameters.Add(new SqlParameter("@OuterBoxLabelPhoto", SqlDbType.NVarChar, 100) { Value = $"%{PSCICQ.PSCIC_OuterBoxLabelPhoto}%" });
                    }

                    using (var command = new SqlCommand(query, connection))
                    {
                        command.Parameters.AddRange(parameters.ToArray());
                        using (var reader = await command.ExecuteReaderAsync())
                        {
                            if (!reader.HasRows)
                            {
                                Logger.Warn("未找到记录");
                                RO.Status = HttpStatusCode.NotFound;
                                RO.Message = "未找到记录";
                                RO.Data = null;
                                return Request.CreateResponse(HttpStatusCode.NotFound, RO);
                            }

                            var products = new List<PackagingStationChangeInformationConfirmation>();
                            int totalCount = 0;
                            while (await reader.ReadAsync())
                            {
                                if (totalCount == 0)
                                {
                                    totalCount = reader.GetInt32(reader.GetOrdinal("TotalCount"));
                                }

                                products.Add(new PackagingStationChangeInformationConfirmation
                                {
                                    PSCIC_ID = reader.GetInt32(reader.GetOrdinal("PSCICID")),
                                    PSCIC_OperatorName = reader.GetString(reader.GetOrdinal("PSCICOperatorName")),
                                    PSCIC_ConfirmationTime = reader.GetDateTime(reader.GetOrdinal("PSCICConfirmationTime")),
                                    PSCIC_LineParting = reader.GetString(reader.GetOrdinal("PSCICLineParting")),
                                    PSCIC_Channel = reader.GetString(reader.GetOrdinal("PSCICChannel")),
                                    PSCIC_PlasticBagFilmPhoto = reader.GetString(reader.GetOrdinal("PSCICPlasticBagFilmPhoto")),
                                    PSCIC_ThermalTransferLabelPhoto = reader.GetString(reader.GetOrdinal("PSCICThermalTransferLabelPhoto")),
                                    PSCIC_ColorBoxPhoto = reader.GetString(reader.GetOrdinal("PSCICColorBoxPhoto")),
                                    PSCIC_ColorBoxLabelPhoto = reader.GetString(reader.GetOrdinal("PSCICColorBoxLabelPhoto")),
                                    PSCIC_OuterBoxLabelPhoto = reader.GetString(reader.GetOrdinal("PSCICOuterBoxLabelPhoto"))
                                });
                            }

                            Logger.Info("查询成功");
                            RO.Status = HttpStatusCode.OK;
                            RO.Message = "OK";
                            RO.Data = products;
                            RO.TotalCount = totalCount;
                            RO.PageNumber = PSCICQ.PageNumber;
                            RO.PageSize = PSCICQ.PageSize;
                            return Request.CreateResponse(HttpStatusCode.OK, RO);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Error("查询失败: " + ex.Message);
                RO.Status = HttpStatusCode.InternalServerError;
                RO.Message = "Error: " + ex.Message;
                RO.Data = null;
                return Request.CreateResponse(HttpStatusCode.InternalServerError, RO);
            }
        }
    }
}
